package com.xiaoq.social.endpoint;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xiaoq.apis.activity.ActivityInfo4Vo;
import com.xiaoq.apis.activity.IActivityApi;
import com.xiaoq.apis.user.IUserApi;
import com.xiaoq.apis.user.UserInfo4SocialVo;
import com.xiaoq.coms.GenericDataResponse;
import com.xiaoq.coms.GenericListResponse;
import com.xiaoq.coms.GenericResponse;
import com.xiaoq.social.entity.FavoriteEntity;
import com.xiaoq.social.service.IFavoriteService;
import com.xiaoq.social.vo.FavoriteListVo;
import com.xiaoq.social.vo.FavoriteVo;
import com.xiaoq.users.entity.UserEntity;
import com.xiaoq.users.entity.UserEntity.RegMethod;
import com.xiaoq.vo.PagingVo;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

@RestController
@RequestMapping("/api/v1/favorite")
public class FavoriteEndpoint {
	
	@Autowired
	private IFavoriteService favoriteSer;
	
	@Reference(interfaceClass=IActivityApi.class, check=false, version="1.0.0")
	private IActivityApi activityDubboApi;
	
	@Reference(interfaceClass=IUserApi.class, check=false, version="1.0.0")
	private IUserApi userDubboApi;
	
	private class FavoriteListResponse extends GenericListResponse<FavoriteListVo>{}
	private class UserFavoriteStatus extends GenericDataResponse<Boolean>{}
	
	
	private static final Logger LOG = LoggerFactory.getLogger(FavoriteEndpoint.class);
	
	@ApiOperation(value = "收藏", notes = "收藏")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "收藏") })
	@PostMapping(value = "/user/{userId}", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> addFavorite(
			@PathVariable(value = "userId", required = false) @ApiParam(value = "userId", required = true) String userId,
			@RequestParam(value = "tgtId", required = true) String tgtId,
			@RequestParam(value = "tgtType", required = true) String tgtType) {
		boolean result = executeLikeitMed(userId, tgtId, tgtType);
		if (result) {
			return GenericResponse.ok();
		} else {
			return GenericResponse.ng("收藏失败！");
		}
	}

	
	
	@ApiOperation(value = "取消收藏", notes = "取消收藏")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "取消收藏") })
	@DeleteMapping(value = "/user/{userId}", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> cancelFavorite(
			@PathVariable(value = "userId", required = false) @ApiParam(value = "userId", required = false) String userId,
			@RequestParam(value = "tgtId", required = true) String tgtId) {

		boolean result = favoriteSer.delFavorite(userId, tgtId);
		if(result){
			return GenericResponse.ok();
		}else{
			return GenericResponse.ng("取消收藏失败！");
		}
		
	}
	
	@ApiOperation(value = "(小程序)取消收藏", notes = "(小程序)取消收藏")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "(小程序)取消收藏") })
	@GetMapping(value = "/users/{userId}", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> cancelFavoriteMini(
			@PathVariable(value = "userId", required = false) @ApiParam(value = "userId", required = false) String userId,
			@RequestParam(value = "tgtId", required = true) String tgtId) {

		boolean result = favoriteSer.delFavorite(userId, tgtId);
		if(result){
			return GenericResponse.ok();
		}else{
			return GenericResponse.ng("取消收藏失败！");
		}
		
	}
	
	
	@ApiOperation(value = "根据userId查询用户收藏列表", notes = "根据userId查询用户收藏列表")
	@ApiResponses({ @ApiResponse(code = 200, response = FavoriteListResponse.class, message = "根据userId查询用户收藏列表") })
	@GetMapping(value = "/user/{userId}", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> getUserFollowList(@PathVariable(value = "userId", required = false)@ApiParam(value="userId",required=false)String userId,@ModelAttribute(value="pvo")PagingVo pvo) {
		// 根据用户Id查询用户收藏列表
		if(StringUtils.isNotEmpty(userId)){
			List<FavoriteEntity> favoriteList = favoriteSer.findFavoriteList(userId, pvo);
			List<FavoriteListVo> favoriteVoList = new ArrayList<>();
			FavoriteListVo favoriteListVo = null;
			Long total = 0L;
			if(favoriteList.size()!=0){
				for(FavoriteEntity favorite:favoriteList){
					favoriteListVo = new FavoriteListVo();
					BeanUtils.copyProperties(favorite, favoriteListVo);
					String rargetType = favorite.getTargetType();
					String id = favorite.getTargetId();
					if(StringUtils.isNotEmpty(id)&&StringUtils.isNotEmpty(rargetType)){
						switch (rargetType) {
						case "20":
							try {
								ActivityInfo4Vo activity = activityDubboApi.findActivityInfo4Vo(id);
								String status = activity.getStatus();
								favoriteListVo.setStatus(status);
							} catch (Exception e) {
								favoriteSer.delFavoriteByTgtId(id);
								favoriteList.remove(favorite);
								LOG.error(e.getMessage(), e);
							}
							break;

						default:
							break;
						}
						favoriteVoList.add(favoriteListVo);
					}
				}
				total = (Long) pvo.getTc();
			}
			return FavoriteListResponse.listAndCount(favoriteVoList, total);
			
		}else{
			return GenericResponse.ng("请先登录！");
		}
		
		
	}
	
	@ApiOperation(value = "是否已经收藏", notes = "是否已经收藏")
	@ApiResponses({ @ApiResponse(code = 200, response = UserFavoriteStatus.class, message = "是否已经收藏") })
	@GetMapping(value = "/user/{userId}/has", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> getFollow(@PathVariable(value = "userId", required = false)@ApiParam(value="userId",required=false) String userId,
			@RequestParam(value = "tgtId", required = true) String tgtId){
		boolean result = favoriteSer.isFavorite(userId, tgtId);
		if(result){
			return UserFavoriteStatus.okWithData(true);
			
		}else{
			return UserFavoriteStatus.okWithData(false);
		}
		
	}
	
	private boolean executeLikeitMed(String userId,String tgtId,String tgtType){
		// 现在只能给文章收藏
		UserInfo4SocialVo userInfo = userDubboApi.getUserInfo4Social(userId);
		userId = userInfo.getId();
		String userLogo = userInfo.getLogoUrl(); 
		String userNickName = userInfo.getNickName();
		if(userId!=null){
			
			switch (tgtType) {
			case "20":	
				// 这里tgtId就是contentId
				ActivityInfo4Vo activityInfo = activityDubboApi.findActivityInfo4Vo(tgtId);;
				
				if(activityInfo!=null){
					FavoriteEntity favorite = new FavoriteEntity();
					 
					
					
					String targetId  = activityInfo.getId();   
					String targetInfo = activityInfo.getContent(); 
					String targetName = activityInfo.getTitle(); 
					String targetLogo = activityInfo.getPostUrl(); 
					String merchantId = activityInfo.getOrgnizerId(); 
					
					favorite.setUserId(userId);
					favorite.setUserLogo(userLogo);
					favorite.setUserNickName(userNickName);
					favorite.setTargetId(targetId);
					favorite.setTargetName(targetName);
					favorite.setTargetInfo(targetInfo);
					favorite.setTargetType(tgtType);
					favorite.setTargetLogo(targetLogo);
					favorite.setMerchantId(merchantId);
					boolean result = favoriteSer.addFavorite(favorite);
					return result;
					
				}
				break;

			default:
				break;
			}
			
		}
				
		return false;
	}

}
